import { post } from '@feidao-factory/send-msg/browser/request';

interface IFileDoc {
	_id: string;
	length: number;
	chunkSize: number;
	uploadDate: Date;
	md5: string;
	filename: string;
	contentType?: string;
	aliases?: string[];
	metadata?: {
		originialFileName?: string;
		productid?: string;
	};
	isDeleted?: boolean;
}

/**
 * 将一个input为file的文件的文件内容转换为base64格式并上传到服务器
 * @param file_server 上传文件服务器，如192.168.40.196
 * @param productid webtest
 * @param file_id 要删除的文件id,上传时返回的filename
 * @param node fileinput结点对象
 * @example const res=await reupload(file_server,productid, file_id, node);
 */
export default function reupload(file_server: string, productid: string, file_id: string, node: HTMLInputElement) {
	return new Promise<IFileDoc>((resolve, reject) => {
		const file = node.files![0];
		const file_name = file.name;
		const r = new FileReader();
		r.readAsDataURL(file);
		r.onload = async (e) => {
			try {
				const file_string = (e.target as any).result as string;
				const ret = await post(`${file_server}/fsweb/reupload?productid=${productid}`, JSON.stringify({
					delfile_name: file_id,
					file_name,
					file_string
				}));
				const files = JSON.parse(ret.responseText);
				resolve(files[0]);
			} catch (e) {
				reject(e);
			}
		};
		r.onerror = async (e) => {
			reject(e);
		};
	});
}
